/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.bitsemart;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;

/**
 * Base de Datos que cumple la función de carrito de la compra. Almacena los vjid de los videojuegos
 * que se añaden a la Base de Datos
 * Ejemplo de Uso:
 * try {
 * BDLocal bdlocal = new BDLocal(this);
 * bdlocal.open();
 * bdlocal.addVideojuego(15);
 * ArrayList<Integer> juegos = bdlocal.fetchAllVideojuegos();
 * bdlocal.deleteVideojuego(15);
 * bdlocal.close();
 * }
 * catch (SQLException e) {
 * e.printStackTrace();
 * }
 */
public class BDLocal {

    public static final String KEY_VJID = "vjid";

    private static final String TAG = "BDLocal";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
            "create table carrito (vjid integer primary key);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "carrito";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS carrito");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public BDLocal(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     * initialization call)
     * @throws android.database.SQLException if the database could be neither opened or created
     */
    public BDLocal open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    /**
     * Inserta el id del videojuego que se incluye en el carrito de la compra
     *
     * @param id VJID del videojuego a insertar en el carrito
     */
    public void addVideojuego(int id) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_VJID, id);

        mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Elimina el id del videojuego del carrito de la compra
     *
     * @param id VJID del videojuego a eliminar del carrito
     * @return true si se ha eliminado, false en otro caso
     */
    public boolean deleteVideojuego(int id) {

        return mDb.delete(DATABASE_TABLE, KEY_VJID + "=" + id, null) > 0;
    }

    /**
     * @return ArrayList con los vjid de todos los videojuegos del carrito
     */
    public ArrayList<Integer> fetchAllVideojuegos() {
        Integer i;
        ArrayList<Integer> vjids = new ArrayList<Integer>();
        Cursor cursor = mDb.query(DATABASE_TABLE, new String[]{KEY_VJID}, null, null, null, null,
                KEY_VJID);
        while (cursor.moveToNext()) {
            vjids.add(cursor.getInt(0));
        }
        return vjids;
    }

    /**
     * @param id
     * @return true si esta el id en la BD, false en caso contrario
     */
    public boolean esta(int id) {
        Cursor cursor = mDb.query(true, DATABASE_TABLE, new String[]{KEY_VJID}, KEY_VJID+"="+id,null,null,null,null,null);
        return cursor.moveToNext();
    }
}
